package com.leetcode.hot100;

import java.util.Arrays;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode.hot100
 * @Author: lei
 * @CreateTime: 2024-03-21  09:06
 * @Description: TODO
 * @Version: 1.0
 */
public class 颜色分类_75 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 0};
        sortColors(nums);
    }

    /**
     * @description: 这是一种暴力无脑解法。
     * @author: lei
     * @date: 2024/3/21 9:19
     * @param: [nums]
     * @return: void
     **/
 /*   public static void sortColors(int[] nums) {
        int count0 = 0, count1 = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                count0++;
            } else if (nums[i] == 1) {
                count1++;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (i < count0) {
                nums[i] = 0;
            } else if (i < (count0 + count1)) {
                nums[i] = 1;
            } else {
                nums[i] = 2;
            }
        }
        System.out.println(Arrays.toString(nums));

    }*/

    /**
     * @description: 根据题意，只有3个数。所以先固定一个中间数1，然后再根据左右指针的方式，实现
     * @author: lei
     * @date: 2024/3/21 9:21
     * @param: [nums]
     * @return: void
     **/
    public static void sortColors(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        for (int i = 0; i <= right; i++) {
            while (nums[i] == 2 && i <= right) {
                int temp = nums[right];
                nums[right] = nums[i];
                nums[i] = temp;
                --right;
            }
            // 当数组中某个元素为0，就需要将该元素提取到数组起始位置
            if (nums[i] == 0) {
                int temp = nums[left];
                nums[left] = nums[i];
                nums[i] = temp;
                ++left;
            }


        }
        System.out.println(Arrays.toString(nums));
    }
}
